package com.ggjp.ribbon.user;

import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author quick
 */
@RestController
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    @LoadBalanced // 3
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.build();
    }

    // 1
    // @Autowired
    // LoadBalancerClient loadBalancerClient;

    @GetMapping("/user/{userId}")
    public JSONObject findById(@PathVariable("userId") Long userId) {

        // 1、使用RestTemplate进行访问订单服务
        // JSONObject jsonObject = restTemplate.getForObject("http://localhost:8080/orders", JSONObject.class);
        // return jsonObject;

        // 2、使用LoadBalancerClient
        // ServiceInstance serviceInstance = loadBalancerClient.choose("order-service");
        // String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/orders");
        // return restTemplate.getForObject(url, JSONObject.class);

        // 3、使用RestTemplate加@LoadBalanced注解进行负载均衡
        return restTemplate.getForObject("http://order-service/orders", JSONObject.class);

    }
}
